import { makeObservable, observable, action } from "mobx";
import { getUserInfo, GetUserInfoAns } from '../../api/user'

interface IUserInfo {
    userId: string;
    avatar: string;
    nickName: string;
}
class UserStore {
    constructor() {
        makeObservable(this)
    }
    @observable isLogin = false
    @observable userInfo: IUserInfo = {
        userId: 'undefined',
        avatar: 'undefined',
        nickName: 'undefined'
    }

    @action.bound login() {
        this.isLogin = true
    }
    @action.bound outLogin() {
        this.isLogin = false
        this.removeUserInfo()
    }

    @action.bound setUserInfo(userId: string, avatar: string, nickName: string) {
        this.userInfo = {
            userId,
            avatar,
            nickName
        }
    }
    @action.bound removeUserInfo() {
        this.userInfo = {
            userId: 'undefined',
            avatar: 'undefined',
            nickName: 'undefined'
        }
    }
    
    // async
    @action.bound getUserInfo() {
        getUserInfo()
            .then(res => {
                const { code, data } = res as unknown as GetUserInfoAns
                if (code === 200) {
                    this.login()
                    this.setUserInfo(data.userId, data.avatar, data.nickName)
                }
            })
            .catch(err => {
                console.log(err);
            })
    }
}

export default UserStore